from flask import request, jsonify, g
from common.my_msg import state_error,state_uncouth
from common.database import get_db_session
from flask_jwt_extended import JWTManager
from common.my_fun import *
from datetime import datetime

jwt = JWTManager()


def before_request():
    g.db_session = get_db_session().__enter__()

def teardown_request(exception):
    if hasattr(g, 'db_session'):
        if exception:
            g.db_session.__exit__(type(exception), exception, exception.__traceback__)
        else:
            g.db_session.__exit__(None, None, None)


def log_error(request, error):
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    with open('error.log', 'r') as f:
        existing_logs = f.read()
    new_log_entry = f'{current_time}\nRequest: {request.method}\nRoute：{request.url}\nERROR：{error}\n\n'
    log_content = new_log_entry + existing_logs
    with open('error.log', 'w') as f:
        f.write(log_content)

def handle_exception(e):
    # 记录错误级别为 ERROR
    log_error(request, e)
    # 回滚数据库事务
    g.db_session.rollback()
    return jsonify(dict(code=state_error(), msg='发生错误'))



@jwt.invalid_token_loader
def invalid_token_callback(error):
    return jsonify({'code':state_uncouth(),'msg':'请重新登录','error':error})

@jwt.expired_token_loader
def expired_token_callback(error):
    return jsonify({'code':state_uncouth(),'msg':'请重新登录','error':error})

@jwt.unauthorized_loader
def missing_token_callback(error):
    return jsonify({'code':state_uncouth(),'msg':'您还未登录','error':error})

def favicon_ico():
    return '未设置图标'




